package dummy.perf;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Scanner;

public class AverageMain {
	private static final String AVERAGE_FILE = "averagenone.txt";
	private static final String INPUT_DIRECTORY = "perfnone";
	public static void main(String[] args) {
		
		//Find the perf directory
		File dir = new File(INPUT_DIRECTORY);
		
		//Create a PerfRun object for each file in the directory
		LinkedList<PerfRun> runs = new LinkedList<PerfRun>();
		for (File f : dir.listFiles()) {
			
			//Ignore .svn
			if (f.getName().contains("svn")) continue;
			
			try {
				Scanner scan = new Scanner(f);
				long sum = 0;
				double avg = 0.0, dev = 0.0;
				
				//Add all longs to list, compute running sum
				LinkedList<Long> list = new LinkedList<Long>();
				while(scan.hasNextLong()) {
					long curr = scan.nextLong();
					list.add(curr);
					sum += curr;
				}
				
				//Compute average
				if (list.size() > 0)
					avg = (double)sum / (double)list.size();
				

				//Compute std dev
				double dev_sum = 0.0;
				for (Long curr : list) {
					dev_sum += Math.pow(curr - avg, 2);
				}
				if (list.size() > 0)
					dev = Math.sqrt(dev_sum/(list.size()-1));
				
				//Add new PerfRun
				runs.add(new PerfRun(list.size(), avg, dev, f.getPath()));
			}
			catch (IOException e) {
				System.err.println("Could not create Scanner for " + f.getAbsolutePath());
				continue;
			}
		}
		try {
			File average = new File(AVERAGE_FILE);
			if (!average.exists()) {
				average.createNewFile();
			}
			FileWriter writer = new FileWriter(average);
			for (PerfRun pr : runs) {
				writer.append(pr.toString() + "\n");
			}
			writer.flush();
			writer.close();
		}
		catch (IOException e) {
			System.out.println("Could not write to file " + AVERAGE_FILE);
		}
	}
	
	private static class PerfRun {
		int count;
		double avg, dev;
		String name;
		public PerfRun(int c, double a, double d, String n) { 
			count = c; avg = a; dev = d; name = n; 
		}
		public String toString() {
			StringBuilder msg = new StringBuilder();
			msg.append("In file: " + name + "\n");
			msg.append("\t" + count + " runs\n");
			msg.append(String.format("\t%8s =%10.4f ms\n", "Avg", avg));
			msg.append(String.format("\t%8s =%10.4f", "StdDev", dev));
			return msg.toString();
		}
	}
}
